import { useEffect, useRef } from 'react';
import { AUTO, Game, Scale } from 'phaser';
import data from './data';
import MarketMap from './marketMap';
import styles from './index.module.less';

const polygons = data.entities.filter((e: any) => e.type === 'LWPOLYLINE' && e.vertices.length > 2 && e.layer === '摊位图框');

const zoom = 100;

const Index = () => {
  const gameRef = useRef<Game>();
  const containerRef = useRef<HTMLDivElement>();
  useEffect(() => {
    const config = {  
      type: AUTO,  
      width: 1000,  
      height: 1000,
      backgroundColor: '#eee',
      mode:  Scale.FIT,
      parent: containerRef.current,
      physics: {  
          default: 'arcade',  
          arcade: {  
              gravity: { y: 0 },
              debug: false  
          }  
      },  
      scene: MarketMap
    };
    
    gameRef.current = new Game(config);
  }, []);

  const handdlerZoom = () => {
    const scene: any = gameRef.current?.scene.getScene('default');
    scene.cameras.main.setZoom(1 / zoom);
  }

  const center = [5000, 5000];

  const handdlerMove = () => {
    const scene: any = gameRef.current?.scene.getScene('default');
    scene.cameras.main.centerOn(center[0], center[1]);
    center[0] += 500;
    center[1] += 500;
  };

  const handdlerAdd = () => {
    for (let index = 0; index < polygons.length; index++) {
      const points = (polygons[index].vertices || [])?.map(item => `${item.x} ${item.y}`);
      handdlerAddPolygon(points.join(' '));
    }
  };

  const handdlerAddPolygon = (points: string) => {
    const scene: any = gameRef.current?.scene.getScene('default');
    const graphics = scene.add.graphics(0, 0);

    graphics.lineStyle(5, 0x000000, 1.0);
    graphics.fillStyle(0xffffff, 1.0);

    // 创建一个多边形对象
    const polygon = new Phaser.Geom.Polygon(points);
    graphics.fillPoints(polygon.points, true);
  }

  return (
    <div>
      <div className={styles.container} ref={containerRef}></div>
      <div onClick={handdlerAdd}>add</div>
      <div onClick={handdlerZoom}>zoom</div>
      <div onClick={handdlerMove}>move</div>
    </div>
  );
};

export default Index;
